package cn.core.tool.aspect;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * Mapper AOP 拦截器 >>> 修改
 */
@Log4j2
@Aspect
@Component
@ConditionalOnProperty(prefix = "proconf", name = "mapper-aspect-update", havingValue = "true")
public class MapperAspectUpdate {

  @Pointcut("execution(public * cn.core..mapper..*.update(..))")
  public void update() {
  }

  @SuppressWarnings("Duplicates")
  @Before("update()")
  public void doBefore(JoinPoint joinPoint) throws Exception {
    try {
      for (Object o : joinPoint.getArgs()) {
        if (o != null) {
          try {
            o.getClass().getMethod("setVersions", Long.class).invoke(o, o.getClass().getMethod("getVersions").invoke(o) != null ? (Long) o.getClass().getMethod("getVersions").invoke(o) + 1l : 1l);
          } catch (NoSuchMethodException e) {
          }
        }
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.error(e.getMessage(), e);
      }
      throw e;
    }
  }

}
